<?php

namespace App\Services\Gallery\Services;

use App\Services\Gallery\Interfaces\BannerServiceInterface;
use App\Services\Gallery\Model\Banner;
use Illuminate\Support\Facades\Auth;

class BannerService implements BannerServiceInterface
{
    public function index($request)
    {
        $keywords = $request['keywords'] ?? '';
        $is_show = $request['is_show'] ?? '';
        $sort = $request['sort'] ?? 'sort';
        $order = $request['order'] ?? 'asc';
        $size = $request['size'] ?? 10;

        $data = Banner::query()
            ->when($keywords, function ($query) use ($keywords) {
                return $query->where('title', 'like', '%' . $keywords . '%');
            })
            ->when($is_show, function ($query) use ($is_show) {
                return $query->where('is_show', $is_show);
            })
            ->orderBy("is_show", "desc")
            ->orderBy($sort, $order)
            ->orderBy("updated_at", "desc")
            ->paginate($size);
        $data->appends($request);

        return $data->toArray();
    }

    public function set($request, $id = 0)
    {
        if ($id) {
            $data = Banner::findOrFail($id);
        } else {
            $data = new Banner();
        }
        $data->user()->associate(Auth::id());
        $data->fill($request)->save();

        return $data->toArray();
    }

    public function get($id)
    {
        return Banner::query()->where('id', $id)->firstOrFail()->toArray();
    }

    public function destroy($id)
    {
        $data = Banner::findOrFail($id);
        $data->delete();
    }
}
